package cgl.narada.service.security.kmc;

import org.apache.log4j.Logger;

import cgl.narada.service.ServiceException;
import cgl.narada.service.time.TimeService;
import cgl.narada.service.time.ntptime.TimeServiceImpl;
import cgl.narada.util.SystemInit;

/**
 * Generates a new TimeStamped Sequence number <br>
 * Created on Oct 27, 2005
 * 
 * @author Harshawardhan Gadgil (hgadgil@grids.ucs.indiana.edu)
 */
public class TSSGenerator {
    static Logger log = Logger.getLogger("TSSGenerator");
    static {
        SystemInit.init();
    }

    private static TimeService ntp = TimeServiceImpl.getInstance();

    private static long ts = -1;
    private static int seq = -1;

    public static synchronized TimeStampedSeqNo generate() {
        long newTS;
        int newSeq;
        try {
            newTS = ntp.getTimestamp();
        } catch (ServiceException e) {
            log.error("Unable to get NTP Timestamp !");
            return null;
        }

        if (newTS > ts) {
            // OK different timestamp
            // So set this as the current time stamp and reset sequence no.
            seq = 0;

        } else {
            // Simply increment sequence no.
            seq++;
        }

        newSeq = seq;
        ts = newTS;
        TimeStampedSeqNo tssn = new TimeStampedSeqNo(newTS, newSeq);
        System.out.println("Generated: " + tssn.toString());
        return tssn;
    }
}
